package com.school.sports.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 统计报表实体类
 * 用于封装各种统计数据
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Report {

    /**
     * 报表ID
     */
    private Long id;

    /**
     * 报表名称
     */
    private String reportName;

    /**
     * 报表类型
     */
    private String reportType;

    /**
     * 报表描述
     */
    private String description;

    /**
     * 统计时间开始
     */
    private LocalDateTime startTime;

    /**
     * 统计时间结束
     */
    private LocalDateTime endTime;

    /**
     * 生成时间
     */
    private LocalDateTime generatedAt;

    /**
     * 生成者ID
     */
    private Long generatedBy;

    /**
     * 报表状态
     */
    private String status;

    /**
     * 报表数据（JSON格式）
     */
    private String reportData;

    /**
     * 报表文件路径
     */
    private String filePath;

    /**
     * 报表类型枚举
     */
    public enum ReportType {
        ENROLLMENT_STATISTICS("报名统计"),
        SCORE_STATISTICS("成绩统计"),
        PROJECT_STATISTICS("项目统计"),
        USER_STATISTICS("用户统计"),
        VOLUNTEER_STATISTICS("志愿者统计"),
        REFEREE_STATISTICS("裁判统计"),
        AWARD_STATISTICS("奖牌统计"),
        OVERVIEW_STATISTICS("总体统计");

        private final String displayName;

        ReportType(String displayName) {
            this.displayName = displayName;
        }

        public String getDisplayName() {
            return displayName;
        }

        /**
         * 根据显示名称获取枚举值
         */
        public static ReportType fromDisplayName(String displayName) {
            for (ReportType type : ReportType.values()) {
                if (type.getDisplayName().equals(displayName)) {
                    return type;
                }
            }
            return null;
        }
    }

    /**
     * 报表状态枚举
     */
    public enum ReportStatus {
        GENERATING("生成中"),
        COMPLETED("已完成"),
        FAILED("生成失败"),
        EXPIRED("已过期");

        private final String displayName;

        ReportStatus(String displayName) {
            this.displayName = displayName;
        }

        public String getDisplayName() {
            return displayName;
        }

        /**
         * 根据显示名称获取枚举值
         */
        public static ReportStatus fromDisplayName(String displayName) {
            for (ReportStatus status : ReportStatus.values()) {
                if (status.getDisplayName().equals(displayName)) {
                    return status;
                }
            }
            return null;
        }
    }

    /**
     * 报表数据（解析后的对象）
     */
    @TableField(exist = false)
    private Map<String, Object> dataMap;

    /**
     * 报表图表数据
     */
    @TableField(exist = false)
    private List<Map<String, Object>> chartData;

    /**
     * 报表统计项
     */
    @TableField(exist = false)
    private List<StatisticItem> statisticItems;

    /**
     * 生成者信息
     */
    @TableField(exist = false)
    private User generator;

    /**
     * 报表格式（Excel、PDF、Word）
     */
    @TableField(exist = false)
    private String format;

    /**
     * 报表大小（字节）
     */
    @TableField(exist = false)
    private Long fileSize;

    /**
     * 下载次数
     */
    @TableField(exist = false)
    private Integer downloadCount;

    /**
     * 获取报表类型显示名称
     */
    public String getReportTypeDisplayName() {
        ReportType typeEnum = ReportType.fromDisplayName(this.reportType);
        return typeEnum != null ? typeEnum.getDisplayName() : this.reportType;
    }

    /**
     * 获取报表状态显示名称
     */
    public String getStatusDisplayName() {
        ReportStatus statusEnum = ReportStatus.fromDisplayName(this.status);
        return statusEnum != null ? statusEnum.getDisplayName() : this.status;
    }

    /**
     * 检查报表是否已完成
     */
    public boolean isCompleted() {
        return ReportStatus.COMPLETED.getDisplayName().equals(this.status);
    }

    /**
     * 检查报表是否生成中
     */
    public boolean isGenerating() {
        return ReportStatus.GENERATING.getDisplayName().equals(this.status);
    }

    /**
     * 检查报表是否生成失败
     */
    public boolean isFailed() {
        return ReportStatus.FAILED.getDisplayName().equals(this.status);
    }

    /**
     * 检查报表是否已过期
     */
    public boolean isExpired() {
        return ReportStatus.EXPIRED.getDisplayName().equals(this.status);
    }

    /**
     * 获取报表状态标签样式（用于前端显示）
     */
    public String getStatusTagType() {
        if (isGenerating()) return "warning";
        if (isCompleted()) return "success";
        if (isFailed()) return "danger";
        if (isExpired()) return "info";
        return "info";
    }

    /**
     * 获取报表文件大小显示
     */
    public String getFileSizeDisplay() {
        if (fileSize == null || fileSize == 0) return "未知";

        if (fileSize < 1024) {
            return fileSize + " B";
        } else if (fileSize < 1024 * 1024) {
            return String.format("%.1f KB", fileSize / 1024.0);
        } else if (fileSize < 1024 * 1024 * 1024) {
            return String.format("%.1f MB", fileSize / (1024.0 * 1024));
        } else {
            return String.format("%.1f GB", fileSize / (1024.0 * 1024 * 1024));
        }
    }

    /**
     * 获取报表时间范围显示
     */
    public String getTimeRangeDisplay() {
        if (startTime == null && endTime == null) {
            return "全部时间";
        } else if (startTime != null && endTime == null) {
            return startTime.toString().substring(0, 10) + " 至今";
        } else if (startTime == null && endTime != null) {
            return "至 " + endTime.toString().substring(0, 10);
        } else {
            return startTime.toString().substring(0, 10) + " 至 " + endTime.toString().substring(0, 10);
        }
    }

    /**
     * 获取报表生成时间显示
     */
    public String getGeneratedTimeDisplay() {
        if (generatedAt == null) return "未知";

        LocalDateTime now = LocalDateTime.now();
        long minutes = java.time.Duration.between(generatedAt, now).toMinutes();
        long hours = java.time.Duration.between(generatedAt, now).toHours();
        long days = java.time.Duration.between(generatedAt, now).toDays();

        if (minutes < 1) {
            return "刚刚";
        } else if (minutes < 60) {
            return minutes + "分钟前";
        } else if (hours < 24) {
            return hours + "小时前";
        } else if (days < 30) {
            return days + "天前";
        } else {
            return generatedAt.toString().substring(0, 10);
        }
    }

    /**
     * 检查报表是否可以下载
     */
    public boolean canDownload() {
        return isCompleted() && filePath != null && !filePath.trim().isEmpty();
    }

    /**
     * 检查报表是否可以删除
     */
    public boolean canDelete() {
        return !isGenerating();
    }

    /**
     * 获取报表摘要
     */
    public String getSummary() {
        StringBuilder summary = new StringBuilder();
        summary.append("报表类型：").append(getReportTypeDisplayName()).append("\n");
        summary.append("时间范围：").append(getTimeRangeDisplay()).append("\n");
        summary.append("生成时间：").append(generatedAt != null ? generatedAt.toString() : "未知").append("\n");
        summary.append("文件大小：").append(getFileSizeDisplay()).append("\n");
        summary.append("下载次数：").append(downloadCount != null ? downloadCount : 0);

        if (generator != null) {
            summary.append("\n生成者：").append(generator.getRealName());
        }

        return summary.toString();
    }

    /**
     * 获取所有可能的报表类型
     */
    public static List<String> getAllReportTypes() {
        return java.util.Arrays.asList(
                ReportType.ENROLLMENT_STATISTICS.getDisplayName(),
                ReportType.SCORE_STATISTICS.getDisplayName(),
                ReportType.PROJECT_STATISTICS.getDisplayName(),
                ReportType.USER_STATISTICS.getDisplayName(),
                ReportType.VOLUNTEER_STATISTICS.getDisplayName(),
                ReportType.REFEREE_STATISTICS.getDisplayName(),
                ReportType.AWARD_STATISTICS.getDisplayName(),
                ReportType.OVERVIEW_STATISTICS.getDisplayName()
        );
    }

    /**
     * 获取所有可能的报表状态
     */
    public static List<String> getAllReportStatuses() {
        return java.util.Arrays.asList(
                ReportStatus.GENERATING.getDisplayName(),
                ReportStatus.COMPLETED.getDisplayName(),
                ReportStatus.FAILED.getDisplayName(),
                ReportStatus.EXPIRED.getDisplayName()
        );
    }

    /**
     * 增加下载次数
     */
    public void incrementDownloadCount() {
        if (downloadCount == null) {
            downloadCount = 1;
        } else {
            downloadCount++;
        }
    }

    /**
     * 检查报表是否需要重新生成
     */
    public boolean needsRegeneration() {
        // 如果报表超过24小时未更新，可能需要重新生成
        if (generatedAt == null) return true;
        return java.time.Duration.between(generatedAt, LocalDateTime.now()).toHours() > 24;
    }

    /**
     * 获取报表图标
     */
    public String getIcon() {
        ReportType typeEnum = ReportType.fromDisplayName(this.reportType);
        if (typeEnum == null) return "document";

        switch (typeEnum) {
            case ENROLLMENT_STATISTICS: return "user";
            case SCORE_STATISTICS: return "medal";
            case PROJECT_STATISTICS: return "list";
            case USER_STATISTICS: return "peoples";
            case VOLUNTEER_STATISTICS: return "user-group";
            case REFEREE_STATISTICS: return "user";
            case AWARD_STATISTICS: return "trophy";
            case OVERVIEW_STATISTICS: return "data-analysis";
            default: return "document";
        }
    }

    /**
     * 获取推荐的导出格式
     */
    public String getRecommendedFormat() {
        ReportType typeEnum = ReportType.fromDisplayName(this.reportType);
        if (typeEnum == null) return "Excel";

        switch (typeEnum) {
            case ENROLLMENT_STATISTICS:
            case SCORE_STATISTICS:
            case USER_STATISTICS:
            case VOLUNTEER_STATISTICS:
            case REFEREE_STATISTICS:
                return "Excel"; // 数据类报表适合Excel
            case PROJECT_STATISTICS:
            case AWARD_STATISTICS:
            case OVERVIEW_STATISTICS:
                return "PDF"; // 汇总类报表适合PDF
            default:
                return "Excel";
        }
    }

    /**
     * 统计项内部类
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StatisticItem {
        private String name;
        private String value;
        private String unit;
        private String trend; // 上升、下降、持平
        private BigDecimal changeRate;
        private String description;

        public String getFormattedValue() {
            if (value == null) return "0";
            if (unit != null && !unit.trim().isEmpty()) {
                return value + " " + unit;
            }
            return value;
        }

        public String getTrendIcon() {
            if (trend == null) return "";
            switch (trend) {
                case "上升": return "📈";
                case "下降": return "📉";
                case "持平": return "➡️";
                default: return "";
            }
        }
    }

    /**
     * 添加统计项
     */
    public void addStatisticItem(String name, String value, String unit, String trend, BigDecimal changeRate, String description) {
        if (statisticItems == null) {
            statisticItems = new java.util.ArrayList<>();
        }
        statisticItems.add(new StatisticItem(name, value, unit, trend, changeRate, description));
    }

    /**
     * 添加统计项（简化版本）
     */
    public void addStatisticItem(String name, String value, String unit) {
        addStatisticItem(name, value, unit, null, null, null);
    }

    /**
     * 获取统计项总数
     */
    public int getStatisticItemCount() {
        return statisticItems != null ? statisticItems.size() : 0;
    }

    /**
     * 检查报表是否有统计数据
     */
    public boolean hasStatisticData() {
        return statisticItems != null && !statisticItems.isEmpty();
    }

    /**
     * 检查报表是否有图表数据
     */
    public boolean hasChartData() {
        return chartData != null && !chartData.isEmpty();
    }

    /**
     * 获取报表标签
     */
    public List<String> getTags() {
        List<String> tags = new java.util.ArrayList<>();

        // 添加状态标签
        tags.add(getStatusDisplayName());

        // 添加类型标签
        tags.add(getReportTypeDisplayName());

        // 添加时间范围标签
        tags.add(getTimeRangeDisplay());

        return tags;
    }
}